package vip.liux.backend.application.serviceImpl.customer;

import org.springframework.stereotype.Service;
import vip.liux.application.dots.ListResultDto;
import vip.liux.application.dots.PagedResultDto;
import vip.liux.backend.application.service.customer.AutoMapperProfile;
import vip.liux.backend.application.service.customer.CustomerDto;
import vip.liux.backend.application.service.customer.CustomerService;
import vip.liux.backend.application.service.customer.QueryCustomerDto;
import vip.liux.backend.application.service.point.PointsAccountDto;
import vip.liux.backend.application.service.point.PointsAccountService;
import vip.liux.backend.infrastructure.jpa.customer.CustomerJpaRepository;
import vip.liux.backend.infrastructure.utils.ListJoinKit;

import java.util.List;

import static vip.liux.application.PageKit.toPage;
import static vip.liux.application.PageKit.toPaged;

@Service
public class CustomerServiceImpl implements CustomerService {
    private final CustomerJpaRepository customerReo;
    private final PointsAccountService pointsAccountService;

    public CustomerServiceImpl(CustomerJpaRepository customerReo, PointsAccountService pointsAccountService) {
        this.customerReo = customerReo;
        this.pointsAccountService = pointsAccountService;
    }

    /**
     * 查询客户列表
     *
     * @param input 查询条件
     * @return 分页结果
     */
    @Override
    public PagedResultDto<CustomerDto> pageList(QueryCustomerDto input) {
        PagedResultDto<CustomerDto> paged = toPaged(customerReo
                .findPageList(input.getSearch(), input.getStart(), input.getEnd(), toPage(input))
                .map(AutoMapperProfile.INSTANCE::toDto)
        );
        List<CustomerDto> items = paged.getItems();

        if (items.isEmpty()) {
            return paged;
        }
        // 批量查询积分账户信息
        List<PointsAccountDto> pointsList = pointsAccountService.getPointsList(items.stream().map(CustomerDto::getId).toList()).getItems();

        // 使用内存左连接填充积分信息
        ListJoinKit.backFill(
                items,
                pointsList,
                CustomerDto::getId,
                PointsAccountDto::getUserId,
                (customerDto, pointsAccountDto) -> customerDto.setPoints(pointsAccountDto.getAvailablePoints()));
        return paged;
    }

    @Override
    public ListResultDto<CustomerDto> findByUserIds(List<Long> userIds) {
        return new ListResultDto<>(AutoMapperProfile.INSTANCE.toDtos(customerReo.findByIdIn(userIds)));
    }
}
